<template>
  <div class="label-management page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">标签管理</h1>
        <p class="page-subtitle">管理系统标签信息，支持标签的增删改查操作</p>
      </div>
      <el-button type="primary" @click="openAddDialog" class="add-btn">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
        </svg>
        新增标签
      </el-button>
    </div>

    <div class="content-card">
      <div class="search-section">
        <el-input
          v-model="searchForm.labelName"
          placeholder="搜索标签名称"
          class="search-input"
          clearable
        >
          <template #prefix>
            <svg class="search-icon" viewBox="0 0 24 24" fill="currentColor">
              <path
                d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
              />
            </svg>
          </template>
        </el-input>
        <el-select
          v-model="searchForm.status"
          placeholder="选择状态"
          clearable
          class="status-select"
        >
          <el-option label="有效" :value="1" />
          <el-option label="无效" :value="0" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table
        :data="labelList"
        style="width: 100%"
        class="label-table"
        v-loading="loading"
        :cell-style="{ paddingLeft: '20px' }"
        :header-cell-style="{ paddingLeft: '20px' }"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="labelName"
          label="标签名称"
          width="200"
          min-width="250"
        />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              size="small"
            >
              {{ scope.row.status === 1 ? "有效" : "无效" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdByName" label="创建人" width="200" />
        <el-table-column prop="createdTime" label="创建时间" width="180" />
        <el-table-column prop="modifiedByName" label="修改人" width="200" />
        <el-table-column prop="modifiedTime" label="修改时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="openEditDialog(scope.row)"
              class="action-btn"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)"
              class="action-btn"
            >
              {{ scope.row.status === 1 ? "禁用" : "启用" }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteLabel(scope.row)"
              class="action-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增标签' : '编辑标签'"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="label-form"
      >
        <el-form-item label="标签名称" prop="labelName">
          <el-input
            v-model="form.labelName"
            placeholder="请输入标签名称，2~8个字符"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">有效</el-radio>
            <el-radio :label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveLabel" :loading="saving">
            {{ dialogType === "add" ? "新增" : "保存" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getWithAuth, postWithAuth } from "@/utils/request";

// 类型定义
interface LabelDTO {
  id?: string;
  labelName: string;
  status: number;
  createdBy?: string;
  createdByName?: string;
  createdTime?: string;
  modifiedBy?: string;
  modifiedByName?: string;
  modifiedTime?: string;
}

interface SearchForm {
  labelName: string;
  status: number | null;
}

// 响应式数据
const loading = ref(false);
const saving = ref(false);
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const labelList = ref<LabelDTO[]>([]);
const formRef = ref();

// 搜索表单
const searchForm = reactive<SearchForm>({
  labelName: "",
  status: null,
});

// 表单数据
const form = reactive<LabelDTO>({
  labelName: "",
  status: 1,
});

// 表单验证规则
const rules = {
  labelName: [
    { required: true, message: "请输入标签名称，最多8个字符", trigger: "blur" },
    {
      min: 2,
      max: 8,
      message: "标签名称长度在 2 到 8 个字符",
      trigger: "blur",
    },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 获取标签列表
const fetchLabelList = async () => {
  loading.value = true;
  try {
    const params = new URLSearchParams();
    if (searchForm.labelName) {
      params.append("labelName", searchForm.labelName);
    }
    if (searchForm.status !== null) {
      params.append("status", searchForm.status.toString());
    }

    const response = await getWithAuth(
      `/internal/label/list?${params.toString()}`
    );

    if (response.code === 0) {
      labelList.value = response.data;
    } else {
      ElMessage.error(response.message || "获取标签列表失败");
    }
  } catch (error) {
    console.error("获取标签列表失败:", error);
    ElMessage.error("获取标签列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  fetchLabelList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.labelName = "";
  searchForm.status = null;
  fetchLabelList();
};

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
  resetForm();
};

// 打开编辑对话框
const openEditDialog = (row: LabelDTO) => {
  dialogType.value = "edit";
  dialogVisible.value = true;
  Object.assign(form, {
    id: row.id,
    labelName: row.labelName,
    status: row.status,
  });
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    labelName: "",
    status: 1,
  });
  formRef.value?.clearValidate();
};

// 保存标签
const saveLabel = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    saving.value = true;

    const url =
      dialogType.value === "add"
        ? "/internal/label/add"
        : "/internal/label/modify";

    const response = await postWithAuth(url, form);

    if (response.code === 0) {
      ElMessage.success(dialogType.value === "add" ? "新增成功" : "修改成功");
      dialogVisible.value = false;
      fetchLabelList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("保存标签失败:", error);
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
};

// 切换状态
const toggleStatus = async (row: LabelDTO) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const actionText = newStatus === 1 ? "启用" : "禁用";

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}标签"${row.labelName}"吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await postWithAuth("/internal/label/modify", {
      id: row.id,
      labelName: row.labelName,
      status: newStatus,
    });

    if (response.code === 0) {
      ElMessage.success(`${actionText}成功`);
      fetchLabelList();
    } else {
      ElMessage.error(response.message || `${actionText}失败`);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("切换状态失败:", error);
      ElMessage.error("操作失败");
    }
  }
};

// 删除标签
const deleteLabel = async (row: LabelDTO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签"${row.labelName}"吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await postWithAuth("/internal/label/delete", {
      id: row.id,
    });

    if (response.code === 0) {
      ElMessage.success("删除成功");
      fetchLabelList();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除标签失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchLabelList();
});
</script>

<style scoped>
.label-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  /* background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); */
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  font-weight: 500;
}

.btn-icon {
  width: 16px;
  height: 16px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 250px;
}

.status-select {
  width: 150px;
}

.search-icon {
  width: 16px;
  height: 16px;
  color: #909399;
}

.label-table {
  margin: 0;
}

.action-btn {
  margin-right: 8px;
}

.action-btn:last-child {
  margin-right: 0;
}

.label-form {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input,
  .status-select {
    width: 100%;
  }
}
</style>
